package com.hhkj.admin.bank.service.extend.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.hhkj.admin.bank.domain.BankQuestionAsso;
import com.hhkj.admin.bank.model.dopo.BankQuestionAssoDo;
import com.hhkj.admin.bank.model.dopo.BankQuestionAssoPo;
import com.hhkj.admin.bank.model.req.BankReq;
import com.hhkj.admin.bank.service.base.BankQuestionAssoService;
import com.hhkj.admin.bank.service.extend.BankQuestionAssoExtendService;
import com.hhkj.admin.question.common.cont.QuestionTypeEnum;
import com.hhkj.admin.question.domain.Question;
import com.hhkj.admin.question.model.req.QuestionReq;
import com.ruoyi.common.base.biz.service.extend.BaseExtendServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * BankQuestionAssoServiceExtendImpl
 *
 * @author HHKJ-SERVER-ZJ
 * @since 2023/6/8 15:52
 */
@Service
public class BankQuestionAssoExtendServiceImpl
        extends BaseExtendServiceImpl<BankQuestionAsso, BankQuestionAssoDo, BankQuestionAssoPo, BankQuestionAssoService>
        implements BankQuestionAssoExtendService
{

    @Override
    public boolean saveBatchForBank(Collection<BankReq> reqCollection)
    {
        ArrayList<BankQuestionAsso> assoDoList = new ArrayList<>();
        for (BankReq bankDo : reqCollection) {
            assoDoList.addAll(this.listAssoFromBank(bankDo));
        }
        if (CollectionUtil.isEmpty(assoDoList)) {
            return false;
        }
        return this.getService().saveBatch(assoDoList);
    }

    @Override
    public boolean saveForBank(BankReq bank)
    {
        List<BankQuestionAsso> assoDoList
                = this.listAssoFromBank(bank);
        if (CollectionUtil.isEmpty(assoDoList)) {
            return false;
        }
        return this.getService().saveBatch(assoDoList);
    }

    /**
     * 从题库中获取题目关联信息
     *
     * @param bank 题库信息
     * @return 题库关联信息
     */
    private List<BankQuestionAsso> listAssoFromBank(BankReq bank)
    {
        List<BankQuestionAsso> assoDoList = new ArrayList<>();
        for (QuestionReq question : bank.getQuestionGroupList()) {
            assoDoList.add(new BankQuestionAsso(bank.getId(), question.getId()));
            if (QuestionTypeEnum.CASE.getCode().equals(question.getTypeCode())) {
                if (CollectionUtil.isEmpty(question.getQuestionList())) {
                    continue;
                }
                // 二级题目
                for (Question secondQuestion : question.getQuestionList()) {
                    assoDoList.add(new BankQuestionAsso(bank.getId(), secondQuestion.getId()));
                }
            }
        }
        return assoDoList;
    }
}
